package com.ihr360.oneclick.util;

import com.ihr360.oneclick.request.SearchRequest;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

/**
 * pageable utils
 *
 * @author tom
 * @date 17-12-19
 */
public class PageableUtils {

    public static Pageable generatePageable(SearchRequest searchRequest) {
        if (searchRequest.getRows() > 100) {
            throw new RuntimeException("最大只能查询100条！");
        }
        int intPage = searchRequest.getPage() <= 0 ? 1 : searchRequest.getPage();
        int intPageSize = searchRequest.getRows() <= 0 || searchRequest.getRows() > 100 ? 100 : searchRequest.getRows();
        if (StringUtils.isNotBlank(searchRequest.getSortField())) {
            return new PageRequest(intPage-1, intPageSize,
                    new Sort(searchRequest.getSortDirection(), searchRequest.getSortField()));
        }
        if (!CollectionUtils.isEmpty(searchRequest.getOrderList())) {
            return new PageRequest(intPage-1, intPageSize, new Sort(searchRequest.getOrderList()));
        }
        return new PageRequest(intPage- 1, intPageSize);
    }

}
